'''
悦·馨保女性特定疾病保险
'''

import sys
sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests
from urllib.parse import urlencode
from common.helper import Helper


class Spider( object ):

    def __init__(self):

        self.mysql = MysqlClient()
        self.name = "悦·馨保女性特定疾病保险"


    #生成产品数据
    def genProductInfo(self):

        #年龄段 18 - 65
        years = [str(i) for i in range( 18,66 )]
        #女性特定疾病保险金
        money = [str(i) for i in range(1,31) ]
        #女性原位癌保证金
        women_cancer = "60000元"
        #女性特定手术金
        women_operation = "12000元"
        #保障期限
        expire = "1年"
        #承诺年龄
        promise = "18-65周岁"
        for v in product( years,money):

            self.mysql.cursor.execute(domain[self.name]["insert_sql"].format( v[0],v[1],women_cancer,women_operation,expire, promise))

            self.mysql._conn.commit()

            print("%s写入数据库成功"%self.name )

    #执行爬虫
    def requestJson(self,dt=None):

        data = {

            "productCode":"NL_NXTDJBX",
            "enterAge":dt["year"],
            "insuedAmout":dt["money"]+"0000"
        }

        r = requests.get( url = domain[self.name]["url"] + urlencode(data ),headers=domain[self.name]["header"])

        if r.status_code == 200 and 'price' in r.json():

            price = Helper.decimalParse( r.json()["price"])
            data = {
                "name":self.name,
                "price":price,
                "id":dt["id"]
            }
            self.mysql.updatePrice( data )

        else:

            # 任务执行失败
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 3
            }
            self.mysql.updateTask(data)

    def main(self):

        while True:

            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)

            if not dt:

                print("产品价格抓取完成~~~")

                return

                # 任务执行状态
            data = {
                "name":self.name,
                "id":dt["id"],
                "state":1
            }
            self.mysql.updateTask( data )

            self.requestJson( dt )

if __name__ == '__main__':

    s = Spider()
    s.genProductInfo()
    s.main()